package com.woniu.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Provider;
import java.security.SecureRandom;

/**
 * AES加解密
 **/
public class AesUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
//    private static final String HEX_KEY = "v0F89mbONyMgEYpK";
    private static Provider provider = new BouncyCastleProvider();

    /**
     * AES加密
     *
     * @param password
     * @param hexKey   16进制的密钥
     * @return
     */
    public static String encrypt(String password, String hexKey) {
        if (StringUtils.isEmpty(password)) {
            return null;
        }
        try {
            Key generateKey = generateKey(hexKey);
            Key key = new SecretKeySpec(generateKey.getEncoded(), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, provider);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(password.getBytes());
            return Base64Utils.encodeToUrlSafeString(doFinal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param cipherText
     * @param hexKey     16进制的密钥
     * @return
     */
    public static String decrypt(String cipherText, String hexKey) {
        if (StringUtils.isEmpty(cipherText)) {
            return null;
        }
        try {
            Key generateKey = generateKey(hexKey);
            Key key = new SecretKeySpec(generateKey.getEncoded(), KEY_ALGORITHM);

            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, provider);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal2 = cipher.doFinal(Base64Utils.decodeFromUrlSafeString(cipherText));
            return new String(doFinal2, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成key
     *
     * @param key
     * @return
     */
    private static Key generateKey(String key) {
        try {
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kg.init(128, secureRandom);
            return kg.generateKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
